package com.qfedu.stussm.service.impl;

import com.qfedu.stussm.dao.AdminDao;
import com.qfedu.stussm.dto.LoginDto;
import com.qfedu.stussm.entity.Admin;
import com.qfedu.stussm.service.intf.AdminService;
import com.qfedu.stussm.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminDao dao;
    @Override
    public R login(LoginDto dto, HttpSession session) {
        //1.验证 验证码是否正确
        if(dto.getCode().equalsIgnoreCase(session.getAttribute("code").toString())){
            //2.查询数据库
            Admin login = dao.login(dto.getA_username());
            //3.验证是否存在
            if (login != null) {
                //4.验证用户状态
                if (login.getA_flag() == 1) {
                    //5.有效，再验证密码
                    if (login.getA_password().equals(dto.getA_password())) {
                        //6.登录成功 存储用户信息到Session
                        session.setAttribute("user", login);
                        login.setA_password("******");
                        return R.ok(login);
                    }
                }
            }
        }
        return R.fail();
    }

    @Override
    public R update(Admin admin) {
        if (dao.update(admin) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }
    @Override
    public R updatePwd(String oldPwd, String newPwd, HttpSession session) {
        Admin user = (Admin) session.getAttribute("user");
        if(user!=null){
            if(dao.updatePwd(user.getA_id(),newPwd,oldPwd)>0){
                //修改成功
                session.removeAttribute("user");
                return R.ok();
            }
        }
        return R.fail();
    }
}
